﻿Imports System
Imports System.Collections.Generic
Imports System.Net
Imports System.Text

Public Class WebClientPost
    Private _client As WebClient
    Private _serviceLocation As Uri
    Private _method As String = "POST"
    Private _data As IList(Of IUrlSerializer) = Nothing

    Public Event PostComplete As EventHandler

    Public Sub New(ByVal serviceLocation As Uri)
        Me._client = New WebClient()
        Me._client.Headers(HttpRequestHeader.Accept) = RequestHeaders.Json
        Me._client.Headers(HttpRequestHeader.ContentType) = RequestHeaders.UrlEncodedForm

        AddHandler Me._client.UploadStringCompleted, AddressOf _client_UploadStringCompleted
        Me._serviceLocation = serviceLocation
        Me._data = New List(Of IUrlSerializer)()
    End Sub

    Public Sub AddDataItem(ByVal dataItem As IUrlSerializer)
        Me._data.Add(dataItem)
    End Sub

    Public Sub Send()
        If Me._data.Count = 0 Then
            Throw New Exception("Data members are required to post form.")
        End If

        Dim sb As New StringBuilder()
        For Each item As IUrlSerializer In Me._data
            sb.Append(item.SerializeToUrlString() + "&")
        Next

        Me._client.UploadStringAsync(Me._serviceLocation, Me._method, sb.ToString())
    End Sub

    Sub _client_UploadStringCompleted(ByVal sender As Object, ByVal e As UploadStringCompletedEventArgs)
        If e.Error Is Nothing AndAlso e.Result = PostResponse.Success Then
            RaiseEvent PostComplete(Me, EventArgs.Empty)
        End If
    End Sub
End Class